"""
#===============================================================================
# License
#===============================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

#===============================================================================
Copyright (c) 2009 bryan p. conrad
bconrad2@gmail.com

Repository Path:    
$HeadURL$

Created on:           Aug 29, 2009
Last Revised on:      $Date$
Version:              $Revision$
ID:                   $Id$
Author:               $Author$ :: (bryan)

#===============================================================================


#===============================================================================
# Documentation
#===============================================================================

"""

#===============================================================================
# Imports
#===============================================================================
import sys
from PyQt4 import QtGui
import time
import os

import JT
import JT.Data2 as Data
from JT.Optimizer import RegularStepGradientDescentOptimizer



class Test(object):
    """
    this module will exercise the new xml element tree data structure. 
    """

    def __init__(self):
        self._connectSuccess = False
        self._uploadData = False
        
    def setup(self,upload=True,logging=True):
#===============================================================================
# Setup Registration
#===============================================================================
        self.reg=JT.MultiIterationRegistration()
        self.reg.drr = JT.DRR()
        # Set additional arguments for cost function
        self.reg.settings['plot'] = True
        self.reg.settings['debug'] = True
        self.reg.settings['logGradientResult'] = False
        self.reg.SetIterations(2)
#===============================================================================
#    Setup Optimizer
#===============================================================================      
        gd = RegularStepGradientDescentOptimizer()
        self.reg.SetOptimizer(gd)
        # Set the cost function
        gd.SetCostFunction(self.reg)
        
    def run(self,data,n_pose=50,method='bpc',vert=0,proj=0,body=0):   
#===============================================================================
# Setup data 
#===============================================================================
        # Pull the Volume and FixedImage elements out of the data structure
        Volume = data.Tree.Frame[vert].Volume[0]
        FixedImage = data.Tree.Frame[vert].FixedImage[proj]       
        
        # Load all of the data elements from the structure into the reg class
        self.reg.LoadCalFile(data.get_path(FixedImage.Cal))
        self.reg.LoadStaFile(data.get_path(Volume.STA))
        self.reg.SetVolumeFileName(data.get_path(Volume))
        self.reg.SetFixedImageFileName(data.get_path(FixedImage))
        self.reg.SetRegionOfInterest(data.get_roi(FixedImage, body))
        self.reg.SetCenter(data.get_center(Volume, body))
                           
        self.reg.SetInitialStepLength(4)
        # set Metric
        self.reg.SetImageMetric(method)
        gd = self.reg.GetOptimizer()
        
        opt_options = data.todict(data.Tree.OptimizerSettings)
        print opt_options
        print type(opt_options)
        gd.ApplySettings(opt_options)
        
        data.Tree.MetricSettings.name = method
        
        # Set the starting pose
        Testing = JT.Testing()
        pose = Testing.GetStartPose(n_pose)
        self.reg.SetInitialPose(pose)
        self.reg._initialStartingPose = pose
        #self.drr._volume_list[0].UseRayCastMapper()
        print "Starting Pose: ", pose
        self.reg.Start()

        initial_pose = pose
        final_pose = self.reg.bestPose
        final_cost = self.reg.bestCost
        Volume.Center[body].initial_pose = initial_pose
        Volume.Center[body].optimized_pose = final_pose
        
        # Write data to file
        log_tag = 'new_data_structure'     #This tag can be used to identify trials
        log_name = time.strftime('%Y%m%d_%H%M%S')+'_'+log_tag+'.xml'
        log_dir = 'C:/Users/bryan/bryan-code/trunk/Tests/log'
        log_path = os.path.join(log_dir,log_name)
        print 'Data written to: ', log_path 
        data.save(log_path)
            

if __name__ == "__main__":
    
    test = Test()
    test.setup(upload=False, logging=True)
    
    # Load in data from an xml file
    data = Data.DataStructure()
    data_path = r'C:\Users\bryan\bryan-code\trunk\Tests\log\new_data_structure.xml' 
    data.load(data_path)
    
    #method_list = ['nmi', 'mi', 'ncc', 'ecc', 'mse', 'ncc', 'gd', 'gc']
    method_list = ['bpc']
    #method_list = ['bpc','gc','mi','nmi','ncc','ecc','ncc','gd','mse']
                   
    vert = [0]
    proj = [0]
    body = [[0,1,2],[0,1,2,3,4]]
    #body=[[1],[1]]
    if 1:
        v=0
        p=1
        b=1
        n_pose=78
        method = 'bpc'
        tag = 'Method: %s, Vert: %s, Proj: %s, Body: %s, Pose: %i' %\
              (method,str(v),str(p),str(b),n_pose)
        print tag
        test.run(data,n_pose=n_pose,method=method,vert=v,proj=p,body=b)
